/*
 * TODO
 */
package com.xtrip.util.parse.xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.xtrip.common.BasicConstant;

/**
 * @project xtrip
 * @author shiming.yao
 * @time 2013-5-27
 */
public class XtripDocumentHelper {

	public static Document createXml(){
		SAXReader reader = new SAXReader();
		DocumentFactory factory = reader.getDocumentFactory();
		Document doc = factory.createDocument();
		return doc;
	}
	public static Document readFile(String fileName) throws DocumentException{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(fileName));
		return doc;
	}
	public static Document read(InputStream is) throws DocumentException{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(is);
		return doc;
	}
	public static Document read(String xmlString) throws DocumentException, UnsupportedEncodingException{
		return read(xmlString, BasicConstant.ENCODE_UTF8);
	}
	public static Document read(String xmlString,String encoding) throws DocumentException, UnsupportedEncodingException{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new ByteArrayInputStream(xmlString.getBytes(encoding)));
		return doc;
	}
	public static void write(Document document,String fileName) throws IOException {
	       // 指定文件
	       XMLWriter writer = new XMLWriter(
	           new FileWriter(fileName)
	       );
	       writer.write( document );
	       writer.close();
	       // 美化格式
	       OutputFormat format = OutputFormat.createPrettyPrint();
	       writer = new XMLWriter( System.out, format );
	       writer.write( document );
	       // 缩减格式
	       format = OutputFormat.createCompactFormat();
	       writer = new XMLWriter( System.out, format );
	       writer.write( document );
	 }
	public static String getNodeAttrVal(Element e,String attr){
		return e.attribute(attr).getValue();
	}
	public static String getNodeAttrVal(Element e,int index){
		return e.attribute(index).getValue();
	}
	public static String getNodeAttrName(Element e,int index){
		return e.attribute(index).getName();
	}
	public static int getNodeCount(Element e,String nodeName){
		return e.elements(nodeName).size();
	}
}
